<template>
  <div class="home">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-dropdown trigger="click" @command="handleMenuClick">
              <el-button type="primary" class="nav-dropdown">
                <el-icon><Menu /></el-icon>
                导航菜单
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="apply">
                    <el-icon><Document /></el-icon>
                    申请创办植物园
                  </el-dropdown-item>
                  <el-dropdown-item command="myGarden">
                    <el-icon><House /></el-icon>
                    我的植物园
                  </el-dropdown-item>
                  <el-dropdown-item command="myProducts">
                    <el-icon><ShoppingBag /></el-icon>
                    我的农产品
                  </el-dropdown-item>
                  <el-dropdown-item command="knowledge">
                    <el-icon><Reading /></el-icon>
                    农产品知识大讲堂
                  </el-dropdown-item>
                  <el-dropdown-item command="expertQA">
                    <el-icon><ChatDotRound /></el-icon>
                    专家问答
                  </el-dropdown-item>
                  <el-dropdown-item v-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 1 && role.applyType === 1)" command="farmApproval">
                    <el-icon><Check /></el-icon>
                    农场项目审批
                  </el-dropdown-item>
                  <el-dropdown-item v-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 1 && role.applyType === 1)" command="userManagement">
                    <el-icon><User /></el-icon>
                    用户管理
                  </el-dropdown-item>
                  <el-dropdown-item v-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 1 && role.applyType === 1)" command="productManagement">
                    <el-icon><Goods /></el-icon>
                    农产品管理
                  </el-dropdown-item>
                  <el-dropdown-item v-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 1 && role.applyType === 1)" command="articleManagement">
                    <el-icon><Document /></el-icon>
                    文章管理
                  </el-dropdown-item>
                  <el-dropdown-item v-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 1 && role.applyType === 1)" command="orderManagement">
                    <el-icon><List /></el-icon>
                    订单管理
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div class="logo">
              <img src="https://susu-plants.oss-cn-beijing.aliyuncs.com/2025-03-04-22-13-33QQ20250304-190757.png" alt="Logo">
            </div>
          </div>
          <div class="header-title">
            <h1>鼠鼠农业网</h1>
          </div>
          <div class="header-right">
            <template v-if="userStore.isLoggedIn">
              <template v-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 1 && role.applyType === 1) && 
                          userStore.userInfo?.userRoles?.length === 1">
                <el-button type="primary" @click="showApplyUsers">用户状态审批</el-button>
              </template>
              <template v-else-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 2 && role.applyType === 1) && 
                          userStore.userInfo?.userRoles?.some(role => role.roleId === 3 && role.applyType === 0) &&
                          userStore.userInfo?.userRoles?.length === 2">
                <el-button type="warning" disabled>审批中</el-button>
              </template>
              <template v-else-if="userStore.userInfo?.userRoles?.some(role => role.roleId === 3 && role.applyType === 1) && 
                          userStore.userInfo?.userRoles?.length === 1">
                <el-button type="success" disabled>专家</el-button>
              </template>
              <el-dropdown @command="handleCommand">
                <span class="user-info">
                  <el-avatar :size="40" :src="userStore.userInfo?.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                  <span class="username">{{ userStore.userInfo?.callName || userStore.userInfo?.userName }}</span>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">个人主页</el-dropdown-item>
                    <el-dropdown-item command="cart">
                      <el-icon><ShoppingCart /></el-icon>
                      我的购物车
                    </el-dropdown-item>
                    <el-dropdown-item command="orders">
                      <el-icon><List /></el-icon>
                      我的订单
                    </el-dropdown-item>
                    <el-dropdown-item command="favorites">
                      <el-icon><Star /></el-icon>
                      我的收藏
                    </el-dropdown-item>
                    <el-dropdown-item command="wallet">我的钱包</el-dropdown-item>
                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template v-else>
              <el-button type="primary" @click="showLoginDialog">登录</el-button>
            </template>
          </div>
        </div>
      </el-header>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 搜索框区域 -->
        <div class="search-section">
          <div class="search-wrapper">
            <h2 class="search-title">探索农产品</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索你感兴趣的农产品..."
              class="search-input"
              :prefix-icon="Search"
              size="large"
            >
              <template #append>
                <el-button type="primary" @click="handleSearch" class="search-button">
                  <el-icon class="search-icon"><Search /></el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
            <div class="search-tags">
              <span class="tag">热门搜索：</span>
              <el-tag 
                v-for="tag in ['有机蔬菜', '新鲜水果', '时令农产', '绿色食品']" 
                :key="tag"
                class="hot-tag"
                @click="searchQuery = tag"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 内容块区域 -->
        <div class="content-row">
          <div class="content-block block-left">
            <div class="categories-container">
              <h2 class="categories-title">商品分类</h2>
              <ul class="categories-list">
                <li v-for="category in categories" 
                    :key="category.categoryId" 
                    class="category-item"
                    @click="handleCategoryClick(category)">
                  {{ category.name }}
                </li>
              </ul>
            </div>
          </div>
          <div class="content-block block-right">
            <div class="latest-products-carousel">
              <h2 class="section-title">最新上架</h2>
              <el-carousel height="450px" :interval="4000" v-if="latestProducts.length > 0">
                <el-carousel-item v-for="product in latestProducts" :key="product.product.productId" @click="handleLatestProductClick(product)">
                  <div class="carousel-item">
                    <img :src="product.images?.[0]?.imageUrl || 'https://via.placeholder.com/400'" :alt="product.product.productName" class="carousel-image">
                    <div class="carousel-info">
                      <h3 class="product-name">{{ product.product.productName }}</h3>
                      <p class="farm-name">{{ product.farm?.farmName || '未知农场' }}</p>
                      <p class="price">¥{{ product.product.price }}</p>
                    </div>
                  </div>
                </el-carousel-item>
              </el-carousel>
              <el-empty v-else :description="getEmptyDescription" class="empty-placeholder" />
            </div>
          </div>
        </div>
        
        <div class="content-row">
          <div class="content-block block-bottom">
            <div class="products-container">
              <h2 class="section-title">热门农产品</h2>
              <div class="products-grid">
                <div v-for="item in displayedProducts" :key="item.product.productId" class="product-card" @click="handleViewProduct(item)">
                  <div class="product-image">
                    <img :src="item.images?.[0]?.imageUrl || 'https://via.placeholder.com/200'" :alt="item.product.productName">
                  </div>
                  <div class="product-info">
                    <h3 class="product-name">{{ item.product.productName }}</h3>
                    <p class="product-description">{{ item.product.productDescription }}</p>
                    <div class="product-meta">
                      <span class="product-price">¥{{ item.product.price }}</span>
                      <span class="product-farm">{{ item.farm?.farmName || '未知农场' }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="currentPage"
                  :page-size="pageSize"
                  :total="total"
                  layout="prev, pager, next"
                  @current-change="handlePageChange"
                  background
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-container>

    <!-- 登录/注册对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentView === 'login' ? '用户登录' : currentView === 'register' ? '用户注册' : '找回密码'"
      width="400px"
      :close-on-click-modal="false"
    >
      <!-- 登录表单 -->
      <el-form v-if="currentView === 'login'" :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>
        <div class="form-options">
          <el-link type="primary" @click="currentView = 'register'">注册账号</el-link>
          <el-link type="primary" @click="currentView = 'forget'">忘记密码？</el-link>
        </div>
      </el-form>

      <!-- 注册表单 -->
      <el-form v-if="currentView === 'register'" :model="registerForm" :rules="registerRules" ref="registerFormRef">
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" placeholder="手机号">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="registerForm.code" placeholder="验证码">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
            <template #append>
              <el-button @click="sendRegisterCode" :disabled="countdown > 0">
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" style="width: 100%">注册</el-button>
        </el-form-item>
        <div class="form-options">
          <el-link type="primary" @click="currentView = 'login'">已有账号？立即登录</el-link>
        </div>
      </el-form>

      <!-- 找回密码表单 -->
      <el-form v-if="currentView === 'forget'" :model="forgetForm" :rules="forgetRules" ref="forgetFormRef">
        <el-form-item prop="phone">
          <el-input v-model="forgetForm.phone" placeholder="手机号">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="forgetForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="forgetForm.code" placeholder="验证码">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
            <template #append>
              <el-button @click="sendForgetCode" :disabled="countdown > 0">
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input v-model="forgetForm.newPassword" type="password" placeholder="新密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleForget" style="width: 100%">重置密码</el-button>
        </el-form-item>
        <div class="form-options">
          <el-link type="primary" @click="currentView = 'login'">返回登录</el-link>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, Message, Document, House, Reading, Menu, Check, ShoppingBag, Search, ShoppingCart, List, ChatDotRound, Star, Goods } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { login, sendCode, findPassword, applyExpert, updateUserApplyType, logout, register, getUserBalance } from '@/api/user'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { getAllCategories } from '@/api/categories'

const userStore = useUserStore()
const dialogVisible = ref(false)
const currentView = ref('login')
const countdown = ref(0)
const applyDialogVisible = ref(false)

const router = useRouter()

const userBalance = ref(0)

// 登录表单
const loginFormRef = ref(null)
const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册表单
const registerFormRef = ref(null)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  code: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}

// 找回密码表单
const forgetFormRef = ref(null)
const forgetForm = reactive({
  phone: '',
  username: '',
  code: '',
  newPassword: ''
})

const forgetRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 添加搜索相关的变量和方法
const searchQuery = ref('')

const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  router.push({
    name: 'SearchResults',
    query: { keyword: searchQuery.value.trim() }
  })
}

// 方法
const showLoginDialog = () => {
  dialogVisible.value = true
  currentView.value = 'login'
}

const showRegisterDialog = () => {
  dialogVisible.value = true
  currentView.value = 'register'
}

const startCountdown = () => {
  countdown.value = 30
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const sendRegisterCode = async () => {
  if (!registerForm.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  try {
    await sendCode(registerForm.phone)
    ElMessage.success('验证码已发送')
    countdown.value = 30
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('验证码发送失败')
  }
}

const sendForgetCode = async () => {
  if (!forgetForm.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  try {
    await sendCode(forgetForm.phone)
    ElMessage.success('验证码已发送')
    startCountdown()
  } catch (error) {
    console.error('验证码发送失败:', error)
    ElMessage.error('验证码发送失败')
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    console.log('开始登录，用户名:', loginForm.username)
    
    const res = await login({
      username: loginForm.username,
      password: loginForm.password
    })
    console.log('登录响应:', res)
    
    // 检查登录响应
    if (!res) {
      console.log('登录失败：响应为空')
      throw new Error('登录失败，联系管理员')
    }
    
    // 检查用户状态
    console.log('用户状态:', res.status)
    if (res.status === 0) {
      console.log('账号已被禁用')
      ElMessage.error('账号已被禁用，请联系管理员')
      // 清除用户信息
      userStore.clearUserInfo()
      // 清除 sessionStorage 中的 userId
      sessionStorage.removeItem('userId')
      return
    }
    
    // 检查是否包含必要的用户信息
    if (!res.userId) {
      console.log('登录失败：缺少用户信息')
      throw new Error('登录失败，联系管理员')
    }
    
    // 将 userId 存入 sessionStorage
    sessionStorage.setItem('userId', res.userId)
    
    // 设置用户信息
    userStore.setUserInfo(res)
    console.log('登录成功，用户信息:', res)
    ElMessage.success('登录成功')
    
    // 关闭登录对话框
    dialogVisible.value = false
  } catch (error) {
    console.error('登录失败:', error)
    console.error('错误详情:', error.response?.data)
    
    // 检查是否是账号禁用的情况
    if (error.response?.data?.status === 0) {
      ElMessage.error('账号已被禁用，请联系管理员')
    } else if (error.response?.data?.message) {
      // 使用后端返回的具体错误消息
      ElMessage.error(error.response.data.message)
    } else {
      // 如果是用户名或密码错误的情况
      ElMessage.error('登录失败，用户名或密码错误')
    }
    
    // 清除用户信息
    userStore.clearUserInfo()
    // 清除 sessionStorage 中的 userId
    sessionStorage.removeItem('userId')
  }
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('开始注册，请求参数:', {
          userName: registerForm.username,
          userPassword: registerForm.password,
          phoneNumber: registerForm.phone,
          code: registerForm.code
        })

        const response = await register({
          userName: registerForm.username,
          userPassword: registerForm.password,
          phoneNumber: registerForm.phone
        }, registerForm.code)

        console.log('注册响应:', response)

        // 检查响应是否成功
        if (!response || response.code === 500 || !response.success) {
          throw new Error(response?.msg || response?.message || '注册失败，请稍后重试')
        }

        // 注册成功
        ElMessage.success(response.msg || '注册成功')
        currentView.value = 'login'
        // 重置表单
        registerForm.username = ''
        registerForm.password = ''
        registerForm.confirmPassword = ''
        registerForm.phone = ''
        registerForm.code = ''
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error(error.response?.data?.message || error.message || '注册失败，请检查注册信息是否正确')
      }
    }
  })
}

const handleForget = async () => {
  if (!forgetFormRef.value) return
  
  await forgetFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await findPassword({
          phone: forgetForm.phone,
          username: forgetForm.username,
          newPassword: forgetForm.newPassword
        })
        ElMessage.success('密码重置成功')
        currentView.value = 'login'
      } catch (error) {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败，请检查手机号和用户名是否正确')
      }
    }
  })
}

// 申请成为专家
const showApplyExpertDialog = async () => {
  try {
    console.log('开始申请专家')
    const res = await updateUserApplyType()
    console.log('申请响应:', res)
    // 更新用户状态和角色记录
    userStore.updateUserStatus(0)
    // 添加申请专家角色记录
    const expertRole = {
      roleId: 2,
      applyType: 1
    }
    userStore.addUserRole(expertRole)
    // 添加普通用户角色记录
    const userRole = {
      roleId: 3,
      applyType: 0
    }
    userStore.addUserRole(userRole)
    ElMessage.success('申请已提交，请等待审核')
  } catch (error) {
    console.error('申请失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error('申请失败，请稍后重试')
  }
}

// 用户登出
const handleLogout = async () => {
  try {
    await logout()
    userStore.clearUserInfo()
    // 清除 sessionStorage 中的 userId
    sessionStorage.removeItem('userId')
    ElMessage.success('退出登录成功')
  } catch (error) {
    console.error('退出登录失败:', error)
    ElMessage.error('退出登录失败，请重试')
  }
}

// 显示用户审批页面
const showApplyUsers = () => {
  router.push('/user-approval')
}

// 获取用户余额
const loadUserBalance = async () => {
  try {
    const res = await getUserBalance()
    userBalance.value = res
  } catch (error) {
    console.error('获取余额失败:', error)
    ElMessage.error('获取余额失败')
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    handleLogout()
  } else if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'wallet') {
    router.push('/wallet')
  } else if (command === 'cart') {
    router.push('/cart')
  } else if (command === 'orders') {
    router.push('/orders')
  } else if (command === 'favorites') {
    router.push('/favorites')
  }
}

const handleMenuClick = (type) => {
  console.log('点击菜单项:', type)
  if (type === 'myGarden') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/my-farms')
  } else if (type === 'apply') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/create-farm')
  } else if (type === 'myProducts') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/my-products')
  } else if (type === 'knowledge') {
    router.push('/knowledge')
  } else if (type === 'expertQA') {
    router.push('/expert-qa')
  } else if (type === 'farmApproval') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/farm-approval')
  } else if (type === 'userManagement') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/user-management')
  } else if (type === 'productManagement') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/product-management')
  } else if (type === 'articleManagement') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/article-management')
  } else if (type === 'orderManagement') {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      showLoginDialog()
      return
    }
    router.push('/order-management')
  }
}

// 添加商品列表数据
const productList = ref([])

// 在 script setup 部分添加分页相关的变量
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const displayedProducts = ref([])

// 修改 loadProducts 方法
const loadProducts = async () => {
  try {
    const response = await request({
      url: '/api/products/list',
      method: 'get'
    })
    console.log('后端返回数据:', response)
    productList.value = response || []
    total.value = productList.value.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    displayedProducts.value = productList.value.slice(start, end)
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 添加分页处理方法
const handlePageChange = (page) => {
  currentPage.value = page
  const start = (page - 1) * pageSize.value
  const end = start + pageSize.value
  displayedProducts.value = productList.value.slice(start, end)
}

// 添加 handleViewProduct 方法
const handleViewProduct = (item) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    showLoginDialog()
    return
  }
  router.push(`/product/${item.farm?.farmId}/${item.product.productId}`)
}

// 添加分类列表数据
const categories = ref([])

// 添加加载分类的方法
const loadCategories = async () => {
  try {
    const response = await getAllCategories()
    console.log('分类数据响应:', response)
    if (Array.isArray(response)) {
      categories.value = response
      console.log('分类数据已加载:', categories.value)
    } else {
      console.warn('获取分类列表失败: 数据格式不正确')
      ElMessage.error('获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 修改分类点击处理方法
const handleCategoryClick = (category) => {
  router.push({
    name: 'CategoryProducts',
    params: { categoryId: category.categoryId },
    query: { name: category.name }
  })
}

// 添加最新上架商品列表数据
const latestProducts = ref([])

// 添加加载最新上架商品的方法
const loadLatestProducts = async () => {
  try {
    const response = await request({
      url: '/api/products/list',
      method: 'get'
    })
    console.log('后端返回商品数据:', response)
    if (response && Array.isArray(response)) {
      // 按创建时间排序并取前4个
      latestProducts.value = response
        .sort((a, b) => new Date(b.product.createdAt) - new Date(a.product.createdAt))
        .slice(0, 4)
    } else {
      latestProducts.value = []
    }
  } catch (error) {
    console.error('获取最新上架商品失败:', error)
    ElMessage.error('获取最新上架商品失败')
  }
}

// 修改空状态提示的显示逻辑
const getEmptyDescription = computed(() => {
  return '暂无最新商品'
})

// 添加 handleLatestProductClick 方法
const handleLatestProductClick = (product) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    showLoginDialog()
    return
  }
  router.push(`/product/${product.farm?.farmId}/${product.product.productId}`)
}

onMounted(() => {
  loadProducts()
  loadCategories()
  loadLatestProducts()
})
</script>

<style scoped>
.home {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-dropdown {
  display: flex;
  align-items: center;
  gap: 5px;
}

.nav-dropdown .el-icon {
  font-size: 18px;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 40px;
  width: auto;
}

.header-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
}

.header-title h1 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.header-right {
  display: flex;
  gap: 20px;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.username {
  font-size: 14px;
  color: #333;
}

.el-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.main-content {
  padding: 40px;
  max-width: 1920px;
  margin: 80px auto 0;
  width: 90%;
}

.search-section {
  background: #f7faf8;
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 40px;
  box-shadow: 0 2px 12px rgba(0, 150, 136, 0.04);
}

.search-title {
  font-size: 28px;
  color: #4a7b51;
  margin: 0 0 20px 0;
  font-weight: 600;
}

.search-wrapper {
  max-width: 900px;
  margin: 0 auto;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  padding-right: 0;
  box-shadow: 0 2px 12px rgba(0, 150, 136, 0.04);
  border-radius: 8px;
  background-color: white;
}

.search-input :deep(.el-input__inner) {
  font-size: 16px;
  height: 48px;
}

.search-input :deep(.el-input__prefix) {
  font-size: 18px;
  margin-right: 8px;
}

.search-input :deep(.el-input-group__append) {
  background-color: #4a7b51;
  border-color: #4a7b51;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  padding: 0 24px;
}

.search-input :deep(.el-input-group__append button:hover) {
  background-color: #5b8c62;
  border-color: #5b8c62;
}

.search-button {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 16px;
  height: 48px;
}

.search-icon {
  font-size: 18px;
}

.search-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 4px 0;
}

.tag {
  color: #4a7b51;
  font-size: 14px;
  font-weight: 500;
}

.hot-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: rgba(74, 123, 81, 0.05);
  border: none;
  color: #4a7b51;
}

.hot-tag:hover {
  background-color: rgba(74, 123, 81, 0.1);
  color: #4a7b51;
  transform: translateY(-1px);
}

.content-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.content-block {
  border-radius: 12px;
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;
  font-size: 24px;
}

/* 左侧方块 - 更窄 */
.block-left {
  flex: 0.4;
  height: 600px;
  background: linear-gradient(135deg, #e0f2f1 0%, #b2dfdb 100%);
  box-shadow: 0 4px 20px rgba(0, 150, 136, 0.15);
}

.block-left:hover {
  transform: translateY(-10px);
  box-shadow: 0 6px 25px rgba(0, 150, 136, 0.25);
}

/* 右侧方块 - 更宽 */
.block-right {
  flex: 1.6;
  height: 600px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  box-shadow: 0 4px 20px rgba(33, 150, 243, 0.15);
}

.block-right:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 25px rgba(33, 150, 243, 0.25);
}

/* 底部长方形 */
.block-bottom {
  width: 100%;
  min-height: 800px;
  background: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 16px;
  padding: 30px;
}

.products-container {
  width: 100%;
  height: 100%;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 30px;
  padding: 20px;
  margin-bottom: 20px;
}

.product-card {
  min-height: 320px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
  flex: 1;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.product-price {
  font-size: 20px;
  font-weight: 600;
  color: #ff6b6b;
}

.product-farm {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 120px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-bottom: 20px;
}

.categories-container {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.categories-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.categories-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-item {
  padding: 15px 20px;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  margin-bottom: 10px;
  background: rgba(255, 255, 255, 0.8);
}

.category-item:hover {
  background: #fff;
  color: #4a7b51;
  transform: translateX(10px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.latest-products-carousel {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.latest-products-carousel .section-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.carousel-item {
  position: relative;
  height: 100%;
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.carousel-item:hover {
  transform: scale(1.02);
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
}

.carousel-info .product-name {
  font-size: 20px;
  margin: 0 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.carousel-info .farm-name {
  font-size: 16px;
  margin: 0 0 8px;
  opacity: 0.9;
}

.carousel-info .price {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  color: #ff6b6b;
}

.empty-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-carousel {
  height: 100%;
}

.el-carousel__item {
  border-radius: 8px;
}
</style> 